<template>
    <el-dialog :close-on-click-modal="false" ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible"
        width="45%" :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
            <el-form-item label="作业类型" prop="workType">
                <el-select v-model="ruleForm.workType" class="w100p" clearable filterable placeholder="请选择作业类型">
                    <el-option label="饲喂作业" value="FEEDING"></el-option>
                    <el-option label="换水作业" value="CHANGE_WATER"></el-option>
                    <el-option label="吊网作业" value="HANGING_NET"></el-option>
                    <el-option label="漏网作业" value="EXPOSED_NET"></el-option>
                    <el-option label="消杀作业" value="DISINFECTION_WATER"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="养殖设施" prop="facilityId">
                <el-select v-model="ruleForm.facilityId" class="w100p" placeholder="请选择养殖设施" @change="getFacilityName">
                    <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
                        :value="item.facilityId" />
                </el-select>
            </el-form-item>
            <el-form-item label="选择批次(已封塘)" prop="batchId">
                <el-select v-model="ruleForm.batchId" class="w100p" placeholder="请选择批次" @change="getBatchName">
                    <el-option v-if="ruleForm.facilityId == item.facilityId && item.status == 'SEALED_POND'"
                        v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
                </el-select>
            </el-form-item>
            <el-row v-if="ruleForm.workType == 'FEEDING'" :gutter="10"
                v-for="item, index in ruleForm.workTaskDetailList" :key="index">
                <el-col :span="11">
                    <el-form-item :label="index == 0 ? '投入物料名称' : ''" :prop="`workTaskDetailList[${index}][materialNo]`"
                        :rules="rules.materialNo">
                        <el-select clearable filterable class=" w100p" v-model="item.materialNo" placeholder="请选择药品"
                            @change="(e) => { getMaterial(e, index) }">
                            <el-option v-for="item, index in materialList" :key="index" :label="item.materialName"
                                :value="item.materialNo"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item :label="index == 0 ? '投入数量' : ''" :prop="`workTaskDetailList[${index}][num]`"
                        :rules="rules.num">
                        <el-input type="number" v-model="item.num" placeholder="请输入参数"
                            :disabled="storageRules == 'THREE'">
                            <template slot="append">{{ item.unitName }}</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="22" v-if="storageRules == 'THREE'">
                    <el-form-item :label="index == 0 ? '选择出库单' : ''"
                        :prop="`workTaskDetailList[${index}][outboundOrderIdList]`" :rules="rules.outboundOrderIdList">
                        <el-select clearable filterable class=" w100p" v-model="item.outboundOrderIdList"
                            placeholder="请选择出库单" @change="getOutboundOrder($event, index)" multiple>
                            <el-option v-for="order, index in outboundOrder" :key="index"
                                :disabled="item.materialNo !== order.materialNo"
                                :label="`仓库名称：${order.stordocName}；物料名称：${order.materialName};出库单号：${order.outboundOrderNo}`"
                                :value="order.outboundOrderId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
                    <i v-show="index" class="icon el-icon-remove-outline" @click.stop="delMaterial(index)"></i>
                </el-col>
            </el-row>
            <el-form-item label="作业人" prop="staffId">
                <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择作业" @change="handleChangePerson">
                    <el-option v-for="item, index in person" :key="index" :label="item.person.name"
                        :value="item.person.personNo + ''"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="作业时间" prop="taskTemplateTime">
                <el-date-picker v-model="ruleForm.taskTemplateTime" type="datetimerange"
                    value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" range-separator="至"
                    start-placeholder="开始时间" end-placeholder="结束时间" align="right">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import jobTaskManagement from '@/api/jobManagment/jobTaskManagement';
import outStorage from "@/api/livestock-manage/sale-manage/out-storage"; // 出库
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        workType: {
            type: String,
            default: () => {
                return 'FEEDING'
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        materialList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    computed: {
        person() {
            return this.$store.state.initData.person || [];
        },
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (value > 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的数值！'))
            }
        }
        return {
            storageRules: '',
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        end.setTime(end.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        end.setTime(end.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        end.setTime(end.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                workType: [
                    { required: true, message: '请选择作业类型', trigger: 'change' }
                ],
                facilityId: [
                    { required: true, message: '请选择设施', trigger: 'change' }
                ],
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                materialNo: [
                    { required: true, message: '请选择物料', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择作业人', trigger: 'change' }
                ],
                taskTemplateTime: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ],
            }
        }
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
            this.storageRules = sessionStorage.storageRules
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.ruleForm = {
                    status: 'ENABLE'
                }
                this.addEditApi = jobTaskManagement.addRecord
                this.addEditName = '添加'
                this.$set(this.ruleForm, 'workTaskDetailList', [{
                    materialName: null, num: null, materialNo: null, unitName: null, outboundOrderIdList: []
                }])
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = {
                    ...this.data,
                    staffId: this.data.personNo || this.data.staffId,
                    taskTemplateTime: [this.data.workStartTime, this.data.workEndTime]
                }
                this.addEditApi = jobTaskManagement.edit
                this.addEditName = '编辑'
                if (this.ruleForm.workTaskDetailList && this.ruleForm.workTaskDetailList.length == 0) {
                    this.$set(this.ruleForm, 'workTaskDetailList', [{
                        materialName: null, num: null, materialNo: null, unitName: null, outboundOrderIdList: []
                    }])
                }
            };
            let outboundOrderIds = []
            this.ruleForm.workTaskDetailList.forEach(e => {
                e.outboundOrderIdList = e.outOrderIds ? e.outOrderIds.split(',') : [];
                outboundOrderIds.concat(e.outboundOrderIdList)
            })
            this.getConditionQuery(outboundOrderIds);
            if (!this.ruleForm.workType) {
                this.$set(this.ruleForm, 'workType', this.workType)
            }
        },
        async getConditionQuery(outboundOrderIds = []) {
            let { data } = await outStorage.conditionQuery({ outboundOrderType: 1, relatedProduction: false, outboundOrderIds });
            this.outboundOrder = data || []
            console.log(data)
        },
        getOutboundOrder(list, index) {
            console.log(list, index)
            let orderList = this.outboundOrder.filter(e => {
                return list.includes(e.outboundOrderId)
            })
            let num = orderList.reduce((sum, item) => sum + item.confirmQuantity, 0);
            console.log(orderList)
            let data = this.ruleForm.workTaskDetailList[index]
            this.$set(this.ruleForm.workTaskDetailList, index, {
                ...data,
                outOrderIds: list.join(),
                num
            })
        },
        getMaterial() {
            this.ruleForm.workTaskDetailList.forEach(item => {
                let result = this.materialList.find(obj => obj.materialNo == item.materialNo);
                item.unitName = result && result.unitName ? result.unitName : '斤';
                console.log(result)
            })
        },
        getFacilityName() {
            let result = this.facilityList.find(obj => obj.facilityId == this.ruleForm.facilityId);
            this.$set(this.ruleForm, 'facilityName', result.facilityName || "");
            this.$set(this.ruleForm, 'batchName', '');
            this.$set(this.ruleForm, 'batchId', '');
        },
        getBatchName() {
            let result = this.batchList.find(obj => obj.batchId == this.ruleForm.batchId);
            this.$set(this.ruleForm, 'batchName', result.batchName);
        },
        handleChangePerson(id) {
            let row = this.person.find(item => Number(item.person.personNo) == id);
            this.$set(this.ruleForm, 'staffName', row.person.name);
        },
        handleGetMaterialName(no) {
            console.log(no)
            let row = this.materialList.find(item => Number(item.materialNo) == Number(no));
            return row.materialName;
        },
        addMaterial() {
            let length = this.ruleForm.workTaskDetailList?.length || 0
            if (length) {
                this.$set(this.ruleForm.workTaskDetailList, length, {
                    materialName: null, num: null, materialNo: null, unitName: null
                })
            }
        },
        delMaterial(index) {
            let list = this.ruleForm.workTaskDetailList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'workTaskDetailList', list)
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (this.ruleForm.workType !== 'FEEDING') {
                        this.ruleForm.workTaskDetailList = []
                    } else if (this.ruleForm.workTaskDetailList && this.ruleForm.workTaskDetailList.length > 0) {
                        this.ruleForm.workTaskDetailList.forEach(item => {
                            item.materialName = this.handleGetMaterialName(item.materialNo)
                        })
                    };
                    let params = {
                        workStartTime: this.ruleForm.taskTemplateTime[0],
                        workEndTime: this.ruleForm.taskTemplateTime[1],
                        workCompleteTime: this.ruleForm.taskTemplateTime[1],
                        workStatus: 'COMPLETE',
                        taskCreate: 'MANUAL_WORK'
                    };
                    delete this.ruleForm.taskTemplateTime;
                    this.addEditApi({ ...this.ruleForm, ...params }).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败';
                        console.log(res)
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg);
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err);
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.warningText = '';
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
        },
        //取消关闭
        cancel() {
            this.resetForm();
            this.$emit("closeDialog");
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); done(); })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.line {
    border-bottom: 1px solid #e6e6e6;
}

.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

::v-deep .noLabel {
    .el-form-item {
        .label {
            display: none;
        }

        .el-form-item__content {
            margin: 0;
        }
    }
}
</style>